/*************************************************************************
	> File Name: vector.c
	> Author: Wang Bo
	> Mail: 1276106221@qq.com
	> Created Time: 2020年12月02日 星期三 15时36分01秒
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "vector.h"


Vector *getNewVector(int size) {
    Vector *v = (Vector *)malloc(sizeof(Vector) * size);
    v->data = (int *)calloc(size, sizeof(int));
    v->size = size;
    v->ind = -1;
    return v;
}

void clearVector(Vector *v) {
    free(v->data);
    free(v);
}

int insertVectorAt(Vector *v, int ind, int val) {
    if (v == NULL || ind < 0 ) return 0;
    if (isVectorEmpty(v) && ind != 0) return 0;
    if (v->ind == v->size - 1) {
        expandVector(v);
        printf("空间不够，扩展Vector至size = %d --", v->size);
    }
    v->ind++;
    for (int i = v->ind; i > ind; --i) {
        v->data[i] = v->data[i - 1];
    }
    v->data[ind] = val;
    return 1;
}

int eraseVectorAt(Vector * v, int ind) {
    if (v == NULL || ind < 0 || ind >= v->ind) return 0;
    for (int i = ind; i <= v->ind - 1; ++i) {
        v->data[i] = v->data[i + 1];
    }
    v->ind--;
    return 1;
}

int pushBackVector(Vector *v, int val) {
    if (v == NULL) return 0;
    if (v->ind == v->size - 1) {
        expandVector(v);
        printf("空间不够，扩展Vector至size = %d --", v->size);
    }
    v->data[++(v->ind)] = val;
    return 1;
}

int expandVector(Vector *v) {
    if (v == NULL) return 0;
    int extSize = v->size;
    int *newdata;
    while (extSize) {
        newdata = (int *)realloc(v->data, sizeof(int) * (v->size + extSize));
        if (newdata) break;
        else  extSize >>= 1;
    }
    if (newdata == NULL) return 0;
    v->data = newdata;
    v->size += extSize;
    return 1;
}
int getVectorSize(Vector *v) {
    return v->size;
}
int getVectorCnt(Vector *v) {
    return v->ind + 1;
}
int isVectorEmpty(Vector *v) {
    return v->ind < 0;
}

void outputVector(Vector *v) {
    printf("[");
    for (int i = 0; i <= v->ind; ++i) {
        i && printf(" ");
        printf("%d", v->data[i]);
    }
    printf("]\n");
}
